package tecpointbenchmark.model.modules;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;
import tecpointbenchmark.model.dto.ResultDTO;

/**
 * Tests the performance of the hard drive.
 * @author Tom & Fredrik
 */
public class HDDModule extends BenchmarkModule {

    private static final String RECORD = "Help I am trapped in a fortune cookie factory\n";
    private static final double MEG = (Math.pow(1024, 2));
    private static final int bufSize = 8192;

    public HDDModule(ResultDTO r) {
    	
        super(r);
        super.setModuleName("HDD");
        super.setShortDescription("Performs a benchmark test on the hard drive");
        super.setLongDescription("Performs a benchmark test on the hard drive by writing "
                + "data to it and then measuring at how many bytes per second the data was written");
    }

    /*
     * Runs the benchmark
     */
    @Override
    public void runBenchmark() {

        // Create temp file and an outputstream
        File fil = new File("HDDtemp.dat");
        FileWriter fw;
        BufferedWriter bw;
        try {
            fw = new FileWriter(fil);
            bw = new BufferedWriter(fw, bufSize);
        } catch (Exception e) {
            System.out.println("File error, benchmark aborted.");
            return;
        }

        // Fetch the result object
        ResultDTO result = super.getResult();

        // Allow benchmarking
        super.setContinueBenchmarking(true);

        result.setTime(new Date().getTime());

        // Set the result to ERROR(2)
        result.setNumber(2);

        long start = System.currentTimeMillis();

        // The boolean variable 'continueBenchmarking' will remain true until
        // the handler changes it's value.
        while (super.getContinueBenchmarking()) {
            try {
                bw.write(RECORD);
            } catch (Exception e) {
                System.out.println(e);
            }
        }

        try {
            bw.flush();
            fw.close();
        } catch (Exception e) {
            System.out.println(e);
        }

        long end = System.currentTimeMillis();
        float time = (end - start) / 1000f;
        
        result.setMessage("File size: " + (int) (fil.length() / MEG) + "MB.  This means we wrote at " + (int) (fil.length() / (MEG * time)) + " MB/s.");

        if (tecpointbenchmark.startup.Main.debug) {
            System.out.println(time + " seconds");
            System.out.println(result.getMessage());
        }

        if (tecpointbenchmark.startup.Main.debug) {
        	System.out.println(result.getPoints());
            System.out.println("Setting score...");
        }

        result.setPoints((int)  (fil.length() / (MEG * time) * 18));
        fil.delete();
    }
}
